package com.terra.ns.imp.system.service.helper

import cn.hutool.core.util.RandomUtil
import com.terra.ns.imp.common.redis.utils.RedisUtils
import com.terra.ns.imp.system.constant.SystemCacheKeys
import com.terra.ns.imp.system.constant.SystemConstants
import com.terra.ns.imp.system.constant.SystemErrorCode
import com.terra.ns.imp.system.exception.SystemServiceException
import com.terra.ns.imp.system.mapper.StDepartmentMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.time.Duration

/**
@author qins
@date 2023/6/20
@desc 系统部门的通用辅助操作
 */
@Component
class StDepartmentHelper {

    @Autowired
    private lateinit var departmentMapper: StDepartmentMapper

    fun generateDeptCode(): String {
        val existCodeSet : HashSet<String> =
            if(RedisUtils.hasKey(SystemCacheKeys.DEPT_CODES_CACHE_KEY))
                RedisUtils.getSet(SystemCacheKeys.DEPT_CODES_CACHE_KEY)
            else
                departmentMapper.selectAllDept().mapNotNull { it.code }.toHashSet()
        var code: String
        do {
            code = RandomUtil.randomNumbers(6)
        } while (existCodeSet.contains(code))
        existCodeSet.add(code)
        RedisUtils.setSet(SystemCacheKeys.DEPT_CODES_CACHE_KEY, existCodeSet.toList(), Duration.ofDays(2))
        return code
    }


    fun computeTopCode(parentCode: String?): String {
        if (parentCode == null || parentCode == SystemConstants.TOP_DEPT_PARENT_CODE) {
            return SystemConstants.TOP_DEPT_PARENT_CODE
        }
        // 查询父级部门信息
        val parentDept =
            departmentMapper.selectByCode(parentCode) ?: throw SystemServiceException(SystemErrorCode.PARENT_DEPT_NOT_EXIST)
        return if (parentDept.topNodeCode == SystemConstants.TOP_DEPT_PARENT_CODE) parentDept.code!! else parentDept.topNodeCode!!
    }

    fun computeNodePath(parentCode: String?, deptCode: String): String {
        if (parentCode == null || parentCode == SystemConstants.TOP_DEPT_PARENT_CODE) {
            return "$deptCode-"
        }
        // 查询父级部门信息
        val parentDept =
            departmentMapper.selectByCode(parentCode) ?: throw SystemServiceException(SystemErrorCode.PARENT_DEPT_NOT_EXIST)
        return "${parentDept.nodePath}${deptCode}-"
    }
}